//package com.lonely.order.support.synchronizer;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.convert.Convert;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.extra.spring.SpringUtil;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.lonely.order.domain.dto.api.GetPurchaseInfoReqDTO;
//import com.lonely.order.domain.dto.api.GetPurchaseInfoResDTO;
//import com.lonely.order.domain.dto.api.QueryProduceOrderIdsReqDTO;
//import com.lonely.order.domain.entity.SysSheinOpenApiSecret;
//import com.lonely.order.service.IMesApiService;
//import com.lonely.order.support.synchronizer.service.SynchronizerOrderService;
//import com.lonely.order.threadlocals.OrderSynchronizedThreadLocal;
//import com.lonely.purchase.domain.entity.SysMaterialPurchase;
//import com.lonely.purchase.enums.MaterialPurchaseEnum;
//import com.lonely.purchase.service.IMaterialPurchaseService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.exception.ExceptionUtils;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
//import org.springframework.beans.BeanUtils;
//
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.concurrent.TimeUnit;
//import java.util.stream.Collectors;
//
///**
// * @author: 黄志标
// * @date: 2025/6/23 13:09
// * @description: 订单同步辅助类
// */
//@Slf4j
//public class OrderSynchronizerHelp {
//
//    private static final IMaterialPurchaseService ORDER_MATERIAL_PURCHASE_ITEM_SERVICE = SpringUtil.getBean(IMaterialPurchaseService.class);
//
//    private static final IMesApiService MES_API_SERVICE = SpringUtil.getBean(IMesApiService.class);
//
//    private static final RedissonClient REDISSON_CLIENT = SpringUtil.getBean(RedissonClient.class);
//
//    private static final SynchronizerOrderService SYNCHRONIZER_ORDER_SERVICE = SpringUtil.getBean(SynchronizerOrderService.class);
//
//    /**
//     * 同步指定日期的订单数据
//     *
//     * @param date
//     */
//    public static void synchronizerOrderByDate(SysSheinOpenApiSecret openApiSecret, Date date) {
//        // 构建rediskey
//        String currentDateStr = DateUtil.format(date, "yyyyMMdd");
//        String lockKey = String.format("synchronizer:orders:%s:%s", openApiSecret.getFactoryId(), currentDateStr);
//        RLock lock = REDISSON_CLIENT.getLock(lockKey);
//        boolean isLocked = false;
//        try {
//            // 尝试获取锁，参数分别是等待时间、锁自动释放时间、时间单位
//            // 不等待，直接尝试获取锁，获取成功则执行逻辑
//            isLocked = lock.tryLock(0, 10, TimeUnit.SECONDS);
//            if (!isLocked) {
//                // 执行需要加锁保护的操作
//                log.debug("同步工厂id：{}，日期：{} 的订单未获取到锁,退出此次同步", openApiSecret.getFactoryId(), currentDateStr);
//                return;
//            }
//
//            // 获取指定日期的订单号
//            List<Long> orderIdsByDate = getOrderIdsByDate(openApiSecret, date);
//
//            // 同步订单
//            SYNCHRONIZER_ORDER_SERVICE.synchronizerOrder(openApiSecret, orderIdsByDate);
//
//            // 同步订单采购数据
//            synchronizerOrderPurchase(openApiSecret, orderIdsByDate);
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//            log.error("同步工厂id：{}，日期：{} 的订单出现异常，异常原因：{}", openApiSecret.getFactoryId(), currentDateStr, ExceptionUtils.getStackTrace(e));
//        } finally {
//            // 确保在finally块中释放锁
//            if (isLocked && lock.isHeldByCurrentThread()) {
//                lock.unlock();
//            }
//        }
//    }
//
//    /**
//     * 同步订单采购数据
//     *
//     * @param openApiSecret
//     * @param orderIds
//     */
//    private static void synchronizerOrderPurchase(SysSheinOpenApiSecret openApiSecret, List<Long> orderIds) {
//        // 有效的订单号集合
//        List<Long> effectiveOrderIds = new ArrayList<>();
//        if (CollUtil.isNotEmpty(orderIds)) {
//            synchronized (OrderSynchronizerHelp.class) {
//                List<SysMaterialPurchase> existsOrderPurchases = ORDER_MATERIAL_PURCHASE_ITEM_SERVICE.list(new LambdaQueryWrapper<SysMaterialPurchase>()
//                        .in(SysMaterialPurchase::getProduceOrderId, orderIds));
//                List<Long> existsOrderPurchaseIds = existsOrderPurchases.stream().map(SysMaterialPurchase::getProduceOrderId).distinct().collect(Collectors.toList());
//
//                // 剔除已存在的订单号
//                effectiveOrderIds = orderIds.stream().filter(x -> !existsOrderPurchaseIds.contains(x)).collect(Collectors.toList());
//            }
//        }
//
//        if (CollUtil.isEmpty(effectiveOrderIds)) {
//            return;
//        }
//
//        // 因为该接口每次订单id最多50条，所以需要切割一下
//        List<List<Long>> split = CollUtil.split(effectiveOrderIds, 50);
//        for (List<Long> currentBatchOrderIds : split) {
//            // 获取指定订单对应的采购信息
//            GetPurchaseInfoReqDTO getPurchaseInfoReqDTO = new GetPurchaseInfoReqDTO();
//            getPurchaseInfoReqDTO.setProduceOrderIdList(currentBatchOrderIds);
//            List<GetPurchaseInfoResDTO> purchaseInfo = MES_API_SERVICE.getPurchaseInfo(openApiSecret, getPurchaseInfoReqDTO);
//            if (CollUtil.isEmpty(purchaseInfo)) {
//                return;
//            }
//
//            List<SysMaterialPurchase> sysMaterialPurchases = new ArrayList<>();
//            purchaseInfo.stream().filter(x -> CollUtil.isNotEmpty(x.getPurchaseInfo())).forEach(x -> {
//                for (GetPurchaseInfoResDTO.PurchaseInfo currentPurchaseInfo : x.getPurchaseInfo()) {
//                    SysMaterialPurchase sysMaterialPurchase = new SysMaterialPurchase();
//                    BeanUtils.copyProperties(currentPurchaseInfo, sysMaterialPurchase);
//                    sysMaterialPurchase.setOrderId(null);
//                    sysMaterialPurchase.setSourceGoodsMaterialId(null);
//                    sysMaterialPurchase.setType(MaterialPurchaseEnum.PurchaseTypeEnum.SHEIN.getType());
//                    sysMaterialPurchase.setProduceOrderId(Convert.toLong(x.getProduceOrderId()));
//                    sysMaterialPurchase.setSupplierColorCode(currentPurchaseInfo.getSupplierColorNum());
//                    sysMaterialPurchase.setFactoryId(openApiSecret.getFactoryId());
//                    sysMaterialPurchase.setCustomerId(openApiSecret.getCustomerId());
//                    sysMaterialPurchase.setStatus(MaterialPurchaseEnum.MaterialPurchaseStatusEnum.TO_BE_PURCHASED.getStatus());
//                    sysMaterialPurchase.setCreateBy(OrderSynchronizedThreadLocal.getCreateBy());
//                    sysMaterialPurchase.setUpdateBy(OrderSynchronizedThreadLocal.getCreateBy());
//                    sysMaterialPurchases.add(sysMaterialPurchase);
//                }
//            });
//            if (CollUtil.isNotEmpty(sysMaterialPurchases)) {
//                ORDER_MATERIAL_PURCHASE_ITEM_SERVICE.saveBatch(sysMaterialPurchases);
//            }
//        }
//
//
//    }
//
//
//    /**
//     * 获取指定日期的订单集合
//     *
//     * @param date
//     * @return
//     */
//    private static List<Long> getOrderIdsByDate(SysSheinOpenApiSecret sheinOpenApiSecret, Date date) {
//        // 1. 获取指定日期订单id集合
//        QueryProduceOrderIdsReqDTO queryProduceOrderIdsReqDTO = new QueryProduceOrderIdsReqDTO();
//        queryProduceOrderIdsReqDTO.setStartTime(DateUtil.beginOfDay(date).toStringDefaultTimeZone());
//        queryProduceOrderIdsReqDTO.setEndTime(DateUtil.endOfDay(date).toStringDefaultTimeZone());
//        return MES_API_SERVICE.queryProduceOrderIds(sheinOpenApiSecret, queryProduceOrderIdsReqDTO).stream().map(Convert::toLong).collect(Collectors.toList());
//    }
//
//
//}
